"""
用户相关的 Pydantic 模型（请求/响应）
"""
from pydantic import BaseModel, Field, field_validator
from typing import Optional
from datetime import datetime


# ==================== 请求模型 ====================

class UserRegisterRequest(BaseModel):
    """用户注册请求"""
    username: str = Field(
        ..., min_length=3, max_length=64,
        description="用户名，3-64个字符"
    )
    password: str = Field(
        ..., min_length=6, max_length=128,
        description="密码，至少6个字符"
    )

    @field_validator('username')
    @classmethod
    def username_alphanumeric(cls, v: str) -> str:
        """验证用户名只包含字母、数字、下划线"""
        if not v.replace('_', '').isalnum():
            raise ValueError('用户名只能包含字母、数字和下划线')
        return v


class UserLoginRequest(BaseModel):
    """用户登录请求"""
    username: str = Field(..., description="用户名")
    password: str = Field(..., description="密码")


class RefreshTokenRequest(BaseModel):
    """刷新 Token 请求"""
    refresh_token: str = Field(..., description="Refresh Token")


# ==================== 响应模型 ====================

class UserResponse(BaseModel):
    """用户基本信息响应（只返回 id 和 username）"""
    id: int
    username: str

    class Config:
        from_attributes = True  # 允许从 ORM 模型创建


class LoginResponse(BaseModel):
    """登录成功响应"""
    token: str
    refresh_token: str
    user: UserResponse


class RefreshTokenResponse(BaseModel):
    """刷新 Token 响应"""
    token: str
    refresh_token: str


class RegisterResponse(BaseModel):
    """注册成功响应"""
    message: str
    user: UserResponse


# ==================== 通用响应 ====================

class ErrorResponse(BaseModel):
    """错误响应"""
    detail: str

